package com.lccviolet;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author LiChaochao
 * @Date 2021/9/10 19:25
 * @Description SynchronousQueueDemo
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                blockingQueue.put(1);
                System.out.println(Thread.currentThread().getName() + "添加1");

                blockingQueue.put(2);
                System.out.println(Thread.currentThread().getName() + "添加2");

                blockingQueue.put(3);
                System.out.println(Thread.currentThread().getName() + "添加3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                blockingQueue.take();
                try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println(Thread.currentThread().getName() + "取出1");

                blockingQueue.take();
                try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println(Thread.currentThread().getName() + "取出2");

                blockingQueue.take();
                try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println(Thread.currentThread().getName() + "取出3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }
}
